<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="设备名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入设备名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceTypeId">
        <el-select v-model="queryParams.deviceTypeId" clearable>
          <el-option
            v-for="item in deviceTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['device:measurement:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Search" @click="toggleSearch">{{
          showSearch ? "隐藏搜索" : "显示搜索"
        }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Refresh" @click="getList"
          >刷新</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="tableData"
      style="min-height: 500px; height: 650px"
    >
      <el-table-column
        prop="deviceName"
        align="center"
        label="设备名称"
        width="150"
      />
      <el-table-column
        prop="deviceCode"
        align="center"
        label="设备编码"
        width="150"
      />
      <el-table-column
        label="设备类型"
        align="center"
        prop="deviceTypeName"
        width="120"
      />
      <el-table-column
        label="经度"
        align="center"
        prop="longitude"
        width="100"
      />
      <el-table-column
        label="维度"
        align="center"
        prop="latitude"
        width="100"
      />
      <el-table-column
        label="能源类型"
        align="center"
        prop="energyType"
        width="120"
      >
        <template #default="scope">
          <el-tag :type="getEnergyTypeTagType(scope.row.energyType)">
            {{ getEnergyTypeName(scope.row.energyType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="规格型号"
        align="center"
        prop="specification"
        width="120"
      />
      <el-table-column
        label="测量范围"
        align="center"
        prop="measurementRange"
        width="120"
      />
      <el-table-column
        label="上数时间(秒)"
        align="center"
        prop="upDataTime"
        width="120"
      >
        <template #default="scope">
          {{ scope.row.upDataTime || "-" }}
        </template>
      </el-table-column>
      <el-table-column
        label="安装位置"
        align="center"
        prop="address"
        width="150"
      />
      <el-table-column prop="state" label="设备状态" width="120">
        <template #default="scope">
          {{ scope.row.state == 0 ? "正常" : "异常" }}
        </template>
      </el-table-column>
      <el-table-column
        label="是否启用"
        align="center"
        prop="isActive"
        width="120"
      >
        <template #default="scope">
          <el-tag :type="scope.row.isActive == 1 ? 'success' : 'danger'">
            {{ scope.row.isActive == 1 ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="重点设备"
        align="center"
        prop="focusState"
        width="120"
      >
        <template #default="scope">
          <el-tag :type="scope.row.focusState == 1 ? 'warning' : 'info'">
            {{ scope.row.focusState == 1 ? "是" : "否" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="实体表"
        align="center"
        prop="isVirtual"
        width="120"
      >
        <template #default="scope">
          {{ scope.row.isVirtual == 1 ? "虚拟表" : "实体表" }}
        </template>
      </el-table-column>
      <el-table-column
        label="摄像头"
        align="center"
        prop="videoType"
        width="120"
      >
        <template #default="scope">
          {{ scope.row.videoType == 0 ? "无" : "有" }}
        </template>
      </el-table-column>
      <el-table-column
        label="备注"
        show-overflow-tooltip
        align="center"
        prop="remark"
        width="150"
      />

      <el-table-column prop="snapshot" label="设备照片" width="120">
        <template #default="scope">
          <el-image
            style="width: 30px; height: 30px"
            :preview-src-list="[scope.row.snapshot]"
            :src="scope.row.snapshot"
            fit="fill"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="150"
      >
        <template #default="scope">
          <el-button
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:measurement:edit']"
            >修改</el-button
          >
          <el-button
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:measurement:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改设备对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="50%"
      append-to-body
      destroy-on-close
    >
      <el-form ref="deviceRef" :model="form" :rules="rules" label-width="120px">
        <!-- 设备基本属性 -->
        <el-collapse v-model="activeCollapse" accordion>
          <el-collapse-item title="设备基本属性" name="basic">
            <el-row v-if="!form.id" :gutter="20">
              <el-col :span="12">
                <el-form-item label="设备类型" prop="deviceTypeId">
                  <el-select
                    v-model="form.deviceTypeId"
                    @change="deviceTypeChange"
                    placeholder="请选择设备类型"
                  >
                    <el-option
                      v-for="item in deviceTypeList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="能源类型" prop="energyType">
                  <el-input
                    v-model="energyTypeDisplay"
                    placeholder="请先选择设备类型"
                    readonly
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="设备名称" prop="deviceName">
                  <el-input
                    v-model="form.deviceName"
                    placeholder="请输入设备名称"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备编码" prop="deviceCode">
                  <el-input
                    v-model="form.deviceCode"
                    placeholder="请输入设备编码"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="规格型号" prop="specification">
                  <el-input
                    v-model="form.specification"
                    placeholder="请输入规格型号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="测量范围" prop="measurementRange">
                  <el-input
                    v-model="form.measurementRange"
                    placeholder="请输入测量范围"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="上数时间(秒)" prop="upDataTime">
                  <el-input-number
                    v-model="form.upDataTime"
                    :min="0"
                    :precision="0"
                    placeholder="请输入上数时间"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="是否启用" prop="isActive">
                  <el-select v-model="form.isActive" placeholder="请选择">
                    <el-option label="启用" :value="1" />
                    <el-option label="禁用" :value="0" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否是实体表" prop="isVirtual">
                  <el-select
                    v-model="form.isVirtual"
                    placeholder="请选择"
                    @change="handleVirtualTypeChange"
                  >
                    <el-option label="实体表" :value="0" />
                    <el-option label="虚拟表" :value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="是否重点设备" prop="focusState">
                  <el-select v-model="form.focusState" placeholder="请选择">
                    <el-option label="是" :value="1" />
                    <el-option label="否" :value="0" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 虚拟表相关字段 -->
            <template v-if="form.isVirtual === 1">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="合表加" prop="addDevices">
                    <el-select
                      v-model="form.addDevices"
                      multiple
                      filterable
                      placeholder="请选择要相加的设备"
                      :loading="deviceSearchLoading"
                      style="width: 100%"
                      @focus="initDeviceOptions"
                      @filter-change="searchDevices"
                    >
                      <el-option
                        v-for="device in deviceOptions"
                        :key="device.id"
                        :label="device.deviceName"
                        :value="device.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="合表减" prop="subtractDevices">
                    <el-select
                      v-model="form.subtractDevices"
                      multiple
                      filterable
                      placeholder="请选择要相减的设备"
                      :loading="deviceSearchLoading"
                      style="width: 100%"
                      @focus="initDeviceOptions"
                      @filter-change="searchDevices"
                    >
                      <el-option
                        v-for="device in deviceOptions"
                        :key="device.id"
                        :label="device.deviceName"
                        :value="device.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
          </el-collapse-item>

          <!-- 设备位置属性 -->
          <el-collapse-item title="设备位置属性" name="location">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="经度" prop="longitude">
                  <el-input v-model="form.longitude" placeholder="请输入经度" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="维度" prop="latitude">
                  <el-input v-model="form.latitude" placeholder="请输入维度" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="安装位置" prop="address">
                  <el-input
                    v-model="form.address"
                    placeholder="请输入安装位置"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>

          <!-- 设备动态属性 -->
          <el-collapse-item title="设备动态属性" name="dynamic">
            <div
              v-if="isLoadingDynamicProps"
              style="text-align: center; padding: 20px"
            >
              <el-icon class="is-loading"><Loading /></el-icon>
              <span style="margin-left: 8px">正在加载设备属性...</span>
            </div>
            <transition-group v-else name="fade-slide" tag="div">
              <el-row
                v-for="(item, index) in form.devicePropertyDataList.filter(
                  (_, i) => i % 2 === 0
                )"
                :key="`${item.id}-${updateKey}`"
                :gutter="20"
              >
                <el-col :span="12">
                  <el-form-item
                    :label="item.propertyName"
                    :prop="item.propertyCode"
                  >
                    <el-input v-model="item.valueString"></el-input>
                  </el-form-item>
                </el-col>
                <el-col
                  :span="12"
                  v-if="form.devicePropertyDataList[index * 2 + 1]"
                >
                  <el-form-item
                    :label="
                      form.devicePropertyDataList[index * 2 + 1].propertyName
                    "
                    :prop="
                      form.devicePropertyDataList[index * 2 + 1].propertyCode
                    "
                  >
                    <el-input
                      v-model="
                        form.devicePropertyDataList[index * 2 + 1].valueString
                      "
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </transition-group>
          </el-collapse-item>

          <!-- 其他属性 -->
          <el-collapse-item title="其他属性" name="other">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="是否有摄像头" prop="videoType">
                  <el-select v-model="form.videoType" placeholder="请选择">
                    <el-option label="无" :value="0" />
                    <el-option label="有" :value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备照片" prop="snapshot">
                  <el-upload
                    class="avatar-uploader"
                    action="/dev-api/common/oss/upload"
                    :show-file-list="false"
                    :headers="{
                      'X-Noodle-Token': getToken(),
                      Authorization: 'Bearer ' + getToken(),
                    }"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img
                      v-if="form.snapshot"
                      :src="form.snapshot"
                      class="avatar"
                    />
                    <el-icon v-else class="avatar-uploader-icon"
                      ><Plus
                    /></el-icon>
                    <template #tip>
                      <div style="font-size: 12px; color: #999">
                        仅支持 JPG/PNG 格式，大小不超过 500KB。<br />
                      </div>
                    </template>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>

            <template v-if="form.videoType === 1">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="摄像头A" prop="videoCodeA">
                    <el-input
                      v-model="form.videoCodeA"
                      placeholder="请输入摄像头A地址"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="摄像头B" prop="videoCodeB">
                    <el-input
                      v-model="form.videoCodeB"
                      placeholder="请输入摄像头B地址"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </template>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input
                    :rows="3"
                    type="textarea"
                    v-model="form.remark"
                    placeholder="请输入备注"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitForm"
            v-hasPermi="['device:measurement:save']"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看设备详情对话框 -->
    <el-dialog
      title="查看设备详情"
      v-model="detailShow"
      width="50%"
      append-to-body
      destroy-on-close
    >
      <el-form :model="form" inline label-width="120px">
        <el-form-item label="设备名称" prop="deviceName">
          <div
            style="
              width: 200px;
              height: 32px;
              line-height: 32px;
              color: rgb(11, 94, 148);
            "
          >
            {{ form.deviceName }}
          </div>
        </el-form-item>
        <el-form-item label="设备编码" prop="deviceCode">
          <div
            style="
              width: 200px;
              height: 32px;
              line-height: 32px;
              color: rgb(11, 94, 148);
            "
          >
            {{ form.deviceCode }}
          </div>
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <div
            style="
              width: 200px;
              height: 32px;
              line-height: 32px;
              color: rgb(11, 94, 148);
            "
          >
            {{ form.longitude }}
          </div>
        </el-form-item>
        <el-form-item label="维度" prop="latitude">
          <div
            style="
              width: 200px;
              height: 32px;
              line-height: 32px;
              color: rgb(11, 94, 148);
            "
          >
            {{ form.latitude }}
          </div>
        </el-form-item>
        <el-form-item label="能源类型" prop="energyType">
          <div
            style="
              width: 200px;
              height: 32px;
              line-height: 32px;
              color: rgb(11, 94, 148);
            "
          >
            {{ getEnergyTypeName(form.energyType) }}
          </div>
        </el-form-item>
        <el-form-item label="规格型号" prop="specification">
          <div
            style="
              width: 200px;
              height: 32px;
              line-height: 32px;
              color: rgb(11, 94, 148);
            "
          >
            {{ form.specification }}
          </div>
        </el-form-item>
        <el-form-item label="测量范围" prop="measurementRange">
          <div
            style="
              width: 200px;
              height: 32px;
              line-height: 32px;
              color: rgb(11, 94, 148);
            "
          >
            {{ form.measurementRange }}
          </div>
        </el-form-item>
        <el-form-item label="上数时间(秒)" prop="upDataTime">
          <div
            style="
              width: 200px;
              height: 32px;
              line-height: 32px;
              color: rgb(11, 94, 148);
            "
          >
            {{ form.upDataTime || "-" }}
          </div>
        </el-form-item>
        <el-form-item label="安装位置" prop="address">
          <div
            style="
              width: 200px;
              height: 32px;
              line-height: 32px;
              color: rgb(11, 94, 148);
            "
          >
            {{ form.address }}
          </div>
        </el-form-item>
        <el-form-item label="是否启用" prop="isActive">
          <div
            style="
              width: 200px;
              height: 32px;
              line-height: 32px;
              color: rgb(11, 94, 148);
            "
          >
            {{ form.isActive == 1 ? "启用" : "禁用" }}
          </div>
        </el-form-item>
        <el-form-item label="是否是实体表" prop="isVirtual">
          <div
            style="
              width: 200px;
              height: 32px;
              line-height: 32px;
              color: rgb(11, 94, 148);
            "
          >
            {{ form.isVirtual == 1 ? "虚拟表" : "实体表" }}
          </div>
        </el-form-item>
        <el-form-item label="是否重点设备" prop="focusState">
          <div
            style="
              width: 200px;
              height: 32px;
              line-height: 32px;
              color: rgb(11, 94, 148);
            "
          >
            {{ form.focusState == 1 ? "是" : "否" }}
          </div>
        </el-form-item>
        <template v-if="form.isVirtual === 1">
          <el-form-item label="合表加" prop="addDevices">
            <div
              style="
                width: 200px;
                height: 32px;
                line-height: 32px;
                color: rgb(11, 94, 148);
              "
            >
              {{ getDeviceNames(form.addDevices) }}
            </div>
          </el-form-item>
          <el-form-item label="合表减" prop="subtractDevices">
            <div
              style="
                width: 200px;
                height: 32px;
                line-height: 32px;
                color: rgb(11, 94, 148);
              "
            >
              {{ getDeviceNames(form.subtractDevices) }}
            </div>
          </el-form-item>
        </template>

        <el-form-item
          v-for="item in form.devicePropertyDataList"
          :key="item.id"
          :label="item.propertyName"
          :prop="item.propertyCode"
        >
          <div
            style="
              width: 200px;
              height: 32px;
              line-height: 32px;
              color: rgb(11, 94, 148);
            "
          >
            {{ item.valueString }}
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      @current-change="currentChange"
      :current-page="pagination.curPage"
      :page-size="pagination.pageSize"
      layout="total, prev, pager, next"
      :total="pagination.total"
    />
  </div>
</template>

<script setup>
import {
  getDeviceTypeList,
  getEmptyByType,
} from "@/api/deviceManage/deviceType";
import {
  getDeviceList,
  delDevice,
  getDeviceDetailById,
  saveDevice,
} from "@/api/deviceManage/device";
import { getToken } from "@/utils/auth";
import { ElMessage, ElMessageBox } from "element-plus";
import { reactive, watch, computed, nextTick, onMounted } from "vue";
import { buildTree } from "@/utils/index";
import { Loading } from "@element-plus/icons-vue";
import {
  ENERGY_TYPE_OPTIONS,
  getEnergyTypeName,
  getEnergyTypeTagType,
} from "@/utils/enums";
const { proxy } = getCurrentInstance();
const tableData = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const detailShow = ref(false);
const updateKey = ref(1);
let deviceTypeList = ref([]);
const isLoadingDynamicProps = ref(false);
const deviceSearchLoading = ref(false);
const deviceOptions = ref([]);
// 计算属性：显示能源类型
const energyTypeDisplay = computed(() => {
  if (!form.deviceTypeId) return "";
  const deviceType = deviceTypeList.value.find(
    (item) => item.id === form.deviceTypeId
  );
  if (deviceType && deviceType.energyType !== undefined) {
    form.energyType = deviceType.energyType;
    return getEnergyTypeName(deviceType.energyType);
  }
  return "";
});

const queryParams = reactive({
  name: "",
  deviceTypeId: null,
});
getDeviceTypeList().then((res) => {
  deviceTypeList.value = res.data.list;
});
const pagination = reactive({
  curPage: 1,
  pageSize: 10,
  total: 0,
});
const kindList = [
  {
    label: "硬件属性",
    value: 0,
  },
  {
    label: "数据属性",
    value: 1,
  },
];
const dataTypeList = [
  {
    label: "字符串",
    value: 0,
  },
  {
    label: "整数型",
    value: 1,
  },
  {
    label: "小数型",
    value: 2,
  },
  {
    label: "布尔型",
    value: 3,
  },
];
const data = reactive({
  rules: {
    deviceName: [
      { required: true, message: "设备名称不能为空", trigger: "blur" },
    ],
    deviceCode: [
      { required: true, message: "设备编码不能为空", trigger: "blur" },
    ],
    deviceTypeId: [
      { required: true, message: "设备类型不能为空", trigger: "change" },
    ],
  },
  propRules: {
    name: [{ required: true, message: "属性名称不能为空", trigger: "blur" }],
    dataCode: [
      { required: true, message: "属性编码不能为空", trigger: "blur" },
    ],
  },
});
function setDynamicProperty() {
  isLoadingDynamicProps.value = true;
  getEmptyByType({ typeId: form.deviceTypeId })
    .then((res) => {
      // 避免频繁更新，先清空再赋值
      form.devicePropertyDataList = [];
      nextTick(() => {
        form.devicePropertyDataList = [...res.data.devicePropertyDataList];
        form.devicePropertyDataList.forEach((d) => {
          if (d.dataFormContent) d.valueString = d.dataFormContent;
        });
        updateKey.value++;
        isLoadingDynamicProps.value = false;
      });
    })
    .catch(() => {
      isLoadingDynamicProps.value = false;
    });
}
function handleView(row) {
  reset();
  getDeviceDetailById(row.id).then((res) => {
    Object.assign(form, res.data);

    // 处理合表加和合表减的回显（用于详情显示）
    if (form.deviceGroupVOs && Array.isArray(form.deviceGroupVOs)) {
      form.addDevices = [];
      form.subtractDevices = [];

      form.deviceGroupVOs.forEach((group) => {
        if (group.modeType === 1) {
          // modeType: 1 是加
          form.addDevices.push(group.groupDeviceId);
        } else if (group.modeType === 2) {
          // modeType: 2 是减
          form.subtractDevices.push(group.groupDeviceId);
        }
      });
    }

    detailShow.value = true;
  });
}
const handleAvatarSuccess = (res, uploadFile) => {
  ElMessage({
    message: "上传成功！",
    type: "success",
  });
  form.snapshot = res.data || res.data.fileUrl || res.data.link || res.data.url;
};
const beforeAvatarUpload = (file) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  const isLt200k = file.size / 1024 < 500;

  if (!isJpgOrPng) {
    ElMessage.error("上传图片格式应为 JPG 或 PNG!");
  }
  if (!isLt200k) {
    ElMessage.error("上传图片大小不能超过 200KB!");
  }
  return isJpgOrPng && isLt200k;
};
const { rules, propRules } = toRefs(data);
const form = reactive({
  id: null,
  deviceName: "",
  deviceCode: "",
  deviceCodeId: null,
  factoryId: "",
  channelId: "",
  deptId: "",
  deviceTypeId: null,
  remark: "",
  snapshot: "",
  latitude: "",
  longitude: "",
  energyType: null, // 根据设备类型自动设置
  specification: "",
  measurementRange: "",
  upDataTime: null, // 上数时间（秒）
  address: "",
  isActive: 1, // 默认启用
  isVirtual: 0, // 默认实体表
  focusState: 0, // 默认非重点设备
  addDevices: [], // 合表加设备ID数组
  subtractDevices: [], // 合表减设备ID数组
  deviceGroupVOs: [], // 传输给后端的设备组对象数组
  devicePropertyDataList: [],
  videoType: 0,
  videoCodeA: "",
  videoCodeB: "",
  videoCodeC: "",
  videoCodeD: "",
  deviceKaidu: "",
});
function getNameByType(type) {
  return dataTypeList.filter((f) => f.value == type)[0].label;
}

// 设备搜索函数
function searchDevices(query) {
  deviceSearchLoading.value = true;

  // 构建搜索参数
  const params = {
    curPage: 1,
    pageSize: 50,
  };

  // 如果有搜索词，添加设备名称搜索（使用name字段进行模糊查询）
  if (query && query.trim() !== "") {
    params.name = query.trim();
  }

  getDeviceList(params)
    .then((response) => {
      deviceOptions.value = response.data.list;
      deviceSearchLoading.value = false;
    })
    .catch(() => {
      deviceSearchLoading.value = false;
    });
}

// 初始化设备选项
function initDeviceOptions() {
  // 默认加载一些设备
  getDeviceList({ curPage: 1, pageSize: 20 })
    .then((response) => {
      deviceOptions.value = response.data.list;
    })
    .catch(() => {
      deviceOptions.value = [];
    });
}

// 虚拟表类型变化处理
function handleVirtualTypeChange(value) {
  if (value === 0) {
    // 切换到实体表，清空虚拟表相关数据
    form.addDevices = [];
    form.subtractDevices = [];
    form.deviceGroupVOs = [];
  }
}

// 获取设备名称（用于详情显示）
function getDeviceNames(deviceIds) {
  if (!deviceIds || deviceIds.length === 0) return "-";
  const names = deviceIds.map((id) => {
    const device = deviceOptions.value.find((d) => d.id === id);
    return device ? device.deviceName : `设备${id}`;
  });
  return names.join(", ");
}

// 构建设备组对象数组
function buildDeviceGroupVOs() {
  const deviceGroupVOs = [];

  // 处理合表加设备
  form.addDevices.forEach((deviceId) => {
    deviceGroupVOs.push({
      groupDeviceId: deviceId,
      modeType: 1, // 1是加
    });
  });

  // 处理合表减设备
  form.subtractDevices.forEach((deviceId) => {
    deviceGroupVOs.push({
      groupDeviceId: deviceId,
      modeType: 2, // 2是减
    });
  });

  form.deviceGroupVOs = deviceGroupVOs;
}
/** 查询列表 */
function getList() {
  loading.value = true;
  let params = { ...pagination, ...queryParams };
  getDeviceList(params)
    .then((response) => {
      tableData.value = response.data.list;
      pagination.total = response.data.totalCount;
      loading.value = false;
    })
    .catch((error) => {
      console.error("获取设备列表失败:", error);
      loading.value = false;
      ElMessage.error("获取设备列表失败，请稍后重试");
    });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  Object.assign(form, {
    id: null,
    deviceName: "",
    deviceCode: "",
    deviceTypeId: null,
    factoryId: "",
    channelId: "",
    deptId: "",
    latitude: "",
    longitude: "",
    energyType: null, // 根据设备类型自动设置
    specification: "",
    measurementRange: "",
    upDataTime: null, // 上数时间（秒）
    address: "",
    isActive: 1, // 默认启用
    isVirtual: 0, // 默认实体表
    focusState: 0, // 默认非重点设备
    addDevices: [], // 合表加设备ID数组
    subtractDevices: [], // 合表减设备ID数组
    deviceGroupVOs: [], // 传输给后端的设备组对象数组
    remark: "",
    snapshot: "",
    devicePropertyDataList: [],
    videoType: 0,
    videoCodeA: "",
    videoCodeB: "",
    videoCodeC: "",
    videoCodeD: "",
    deviceKaidu: "",
  });
  if (deviceTypeList.length) form.deviceTypeId = null; // 不自动选择设备类型
  proxy.resetForm("deviceRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.name = "";
  queryParams.deviceTypeId = null;
  handleQuery();
}

/** 切换搜索显示/隐藏 */
function toggleSearch() {
  showSearch.value = !showSearch.value;
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  open.value = true;
  title.value = "新增设备";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getDeviceDetailById(row.id).then((res) => {
    Object.assign(form, res.data);

    // 处理合表加和合表减的回显
    if (form.deviceGroupVOs && Array.isArray(form.deviceGroupVOs)) {
      form.addDevices = [];
      form.subtractDevices = [];

      form.deviceGroupVOs.forEach((group) => {
        if (group.modeType === 1) {
          // modeType: 1 是加
          form.addDevices.push(group.groupDeviceId);
        } else if (group.modeType === 2) {
          // modeType: 2 是减
          form.subtractDevices.push(group.groupDeviceId);
        }
      });
    }

    open.value = true;
    title.value = "修改设备";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deviceRef"].validate((valid) => {
    if (valid) {
      // 如果是虚拟表，构建设备组对象数组
      if (form.isVirtual === 1) {
        buildDeviceGroupVOs();
      }

      // 调试：打印提交的表单数据
      console.log("提交的表单数据:", form);
      console.log("upDataTime 字段值:", form.upDataTime);

      if (form.id) {
        saveDevice(form).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        saveDevice(form).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  ElMessageBox.confirm(
    '是否确认删除名称为"' + row.deviceName + '"的数据项?',
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      delDevice([row.id]).then((res) => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      });
    })
    .catch(() => {
      ElMessage.info("取消删除");
    });
}
function currentChange(e) {
  pagination.curPage = e;
  getList();
}
function deviceTypeChange(e) {
  if (e) {
    // 根据选择的设备类型自动设置能源类型
    const selectedDeviceType = deviceTypeList.value.find(
      (item) => item.id === e
    );
    if (selectedDeviceType && selectedDeviceType.energyType !== undefined) {
      form.energyType = selectedDeviceType.energyType;
    }

    // 使用 nextTick 确保 DOM 更新完成后再执行
    nextTick(() => {
      setDynamicProperty();
    });
  }
}
function filterNodeMethod(value, data) {
  if (!value) return true;
  // 支持多种字段名的搜索，不区分大小写
  const searchText = data.label || data.name || data.deptName || "";
  const result = searchText.toLowerCase().includes(value.toLowerCase());
  return result;
}

// 页面初始化
onMounted(() => {
  getDeviceTypeList().then((res) => {
    deviceTypeList.value = res.data.list;
  });
  getList();
  // 初始化设备选项
  initDeviceOptions();
});
</script>
<style lang="scss" scoped>
@import "@/assets/styles/variables.module.scss";

.app-container {
  padding: 10px 20px;
  background: $base-menu-background;
  min-height: 100vh;
}

// 搜索表单样式
.el-form {
  background: #ffffff;
  padding: 10px 20px;
  border-radius: 8px;
  margin-bottom: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .el-button {
    border-radius: 6px;
    font-weight: 500;

    &.el-button--primary {
      background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
      border: none;
      color: #ffffff;

      &:hover {
        background: linear-gradient(135deg, #3bc4b3 0%, #2aa3b8 100%);
        color: #ffffff;
      }
    }

    &:not(.el-button--primary) {
      background: linear-gradient(135deg, #909399 0%, #73767a 100%);
      border: none;
      color: #ffffff;

      &:hover {
        background: linear-gradient(135deg, #82848a 0%, #6c6e72 100%);
        color: #ffffff;
      }
    }
  }
}

// 按钮组样式
.mb8 {
  margin-bottom: 10px;
  margin-left: 0 !important;
  margin-right: 0 !important;
  background: #ffffff;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .el-button {
    border-radius: 6px;
    font-weight: 500;

    &.el-button--primary {
      background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
      border: none;
      color: #ffffff;

      &:hover {
        background: linear-gradient(135deg, #3bc4b3 0%, #2aa3b8 100%);
        color: #ffffff;
      }
    }

    &.el-button--primary.is-plain {
      background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
      border: none;
      color: #ffffff;

      &:hover {
        background: linear-gradient(135deg, #3bc4b3 0%, #2aa3b8 100%);
        color: #ffffff;
      }
    }
  }
}

// 操作按钮样式
:deep(.el-button--text) {
  color: #4fdaca !important;
  font-weight: 600 !important;
  position: relative !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
  border-radius: 6px !important;
  padding: 6px 12px !important;

  &:hover {
    color: #32b7cb !important;
    background: linear-gradient(
      135deg,
      rgba(79, 218, 202, 0.1) 0%,
      rgba(50, 183, 203, 0.1) 100%
    ) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 2px 8px rgba(79, 218, 202, 0.2) !important;
  }

  &:active {
    transform: translateY(0) !important;
    box-shadow: 0 1px 4px rgba(79, 218, 202, 0.3) !important;
  }
}

// 更具体的操作按钮样式选择器
::v-deep(.el-button.el-button--text) {
  color: #4fdaca !important;
  font-weight: 600 !important;
  font-size: 13px !important;
  padding: 8px 16px !important;
  margin: 0 6px !important;
  border-radius: 8px !important;
  border: 1px solid transparent !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
  position: relative !important;
  overflow: hidden !important;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
    transition: left 0.3s ease;
    z-index: -1;
  }

  &:hover {
    color: #ffffff !important;
    transform: translateY(-2px) !important;
    box-shadow: 0 4px 12px rgba(79, 218, 202, 0.4) !important;
    border-color: #4fdaca !important;
    background: transparent !important;

    &::before {
      left: 0;
    }
  }

  &:active {
    transform: translateY(0) !important;
    box-shadow: 0 2px 6px rgba(79, 218, 202, 0.3) !important;
  }
}

// 上传组件样式
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  &:hover {
    border-color: #4fdaca;
  }
}

:deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}

.el-select {
  width: 220px !important;
}
.el-input {
  width: 100% !important;
}
.el-textarea {
  width: 100% !important;
}
.el-tree-select {
  width: 100% !important;
}

// 折叠面板样式
:deep(.el-collapse) {
  border: none;

  .el-collapse-item {
    margin-bottom: 16px;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    overflow: hidden;

    .el-collapse-item__header {
      background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
      border: none;
      padding: 0 20px;
      height: 48px;
      line-height: 48px;
      font-weight: 600;
      color: #2c3e50;
      font-size: 14px;

      &:hover {
        background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
      }

      .el-collapse-item__arrow {
        color: #4fdaca;
        font-weight: bold;
      }
    }

    .el-collapse-item__wrap {
      border: none;

      .el-collapse-item__content {
        padding: 20px;
        background: #ffffff;
        border-top: 1px solid #e4e7ed;
      }
    }
  }
}

/* 过渡动画样式 */
.fade-slide-enter-active,
.fade-slide-leave-active {
  transition: all 0.3s ease;
}
.fade-slide-enter-from {
  opacity: 0;
  transform: translateX(10px);
}
.fade-slide-leave-to {
  opacity: 0;
  transform: translateX(-10px);
}
.fade-slide-move {
  transition: transform 0.3s ease;
}

// 表格样式
.main-table {
  width: 100%;

  // 表头样式优化
  :deep(.el-table th) {
    padding: 8px 0;
    background: #f8f9fa;
    font-weight: 600;
    white-space: nowrap; // 防止表头文字换行
    text-overflow: ellipsis;
    overflow: hidden;
  }

  // 表格单元格样式优化
  :deep(.el-table td) {
    padding: 8px 0;
    white-space: nowrap; // 防止单元格内容换行
    text-overflow: ellipsis;
    overflow: hidden;
  }

  // 固定列样式
  ::v-deep(.el-table__fixed-right) {
    box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
    z-index: 20;

    .el-table__header-wrapper {
      z-index: 11;
      position: relative;
    }

    .el-table__body-wrapper {
      z-index: 10;
      position: relative;
    }

    // 确保表头单元格正确显示
    .el-table__header th {
      background: #f8f9fa !important;
      position: relative;
      z-index: 12;
    }
  }

  :deep(.el-table__fixed-left) {
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
    z-index: 10;

    .el-table__header-wrapper {
      z-index: 11;
      position: relative;
    }

    .el-table__body-wrapper {
      z-index: 10;
      position: relative;
    }

    // 确保表头单元格正确显示
    .el-table__header th {
      background: #f8f9fa !important;
      position: relative;
      z-index: 12;
    }
  }

  // 操作按钮在固定列中的样式
  :deep(.el-table__fixed-right .el-button--text) {
    font-size: 12px !important;
    padding: 4px 8px !important;
    margin: 0 2px !important;
    color: #4fdaca !important;
    font-weight: 600 !important;

    &:hover {
      color: #32b7cb !important;
      background: linear-gradient(
        135deg,
        rgba(79, 218, 202, 0.1) 0%,
        rgba(50, 183, 203, 0.1) 100%
      ) !important;
    }
  }
}
</style>
<style>
:deep(.custom-tree-select-dropdown) {
  max-height: 300px !important;
  min-width: 280px !important;
}
:deep(.custom-tree-select-dropdown .el-tree-select-dropdown__list) {
  max-height: 280px !important;
  overflow-y: auto !important;
  min-width: 280px !important;
}
:deep(.custom-tree-select-dropdown .el-scrollbar__view) {
  max-height: 280px !important;
  min-width: 280px !important;
}
:deep(.custom-tree-select-dropdown .el-tree) {
  max-height: 280px !important;
  overflow-y: auto !important;
  min-width: 280px !important;
}
:deep(.el-tree-select-dropdown__list) {
  max-height: 280px !important;
  overflow-y: auto !important;
  min-width: 280px !important;
}
:deep(.el-tree-node__content) {
  white-space: nowrap !important;
  min-width: 250px !important;
}
:deep(.el-tree-node__label) {
  white-space: nowrap !important;
  overflow: visible !important;
}
</style>
